package org.mspring.mlog.web.security.interceptors;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.mspring.mlog.entity.security.User;
import org.mspring.mlog.web.security.SecurityUtils;
import org.mspring.mlog.web.security.interceptors.handlers.AbstractFailureHandler;
import org.mspring.mlog.web.security.interceptors.handlers.RedirectFailureHandler;
import org.mspring.platform.utils.StringUtils;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.util.AntPathRequestMatcher;
import org.springframework.security.web.util.RequestMatcher;

/**
 * 用于处理UCenter用户权限，当值登录后用户跨页面攻击他人后台页面
 * 
 * @author Gao Youbo
 * @since 2013年7月11日
 */
public class UCenterAdminSecurityInterceptor extends AbstractSecurityInterceptor {

    /**
     * 登录失败跳转地址
     */
    private String failureUrl;

    public String getFailureUrl() {
        return failureUrl;
    }

    public void setFailureUrl(String failureUrl) {
        this.failureUrl = failureUrl;
    }

    @Override
    public boolean exec(FilterInvocation fi) throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletRequest request = fi.getRequest();

        RequestMatcher urlMatcher = new AntPathRequestMatcher("/u/*/admin/**");
        if (urlMatcher.matches(request)) {
            User currentUser = SecurityUtils.getCurrentUser(request); // 当前登录用户
            if (currentUser == null) {
                return false;
            }
            // 从请求地址中获取当前访问的UCenter对应的用户名
            
            String url = request.getRequestURI();
            String contextPath = request.getContextPath();
            if (StringUtils.isNotBlank(contextPath)) {
                url = StringUtils.substringAfter(url, contextPath);
            }
            String name = StringUtils.split(url, "/")[1];

            // String name = "";
            // String url = request.getRequestURI();
            // Matcher m =
            // Pattern.compile("\\/.+\\/u\\/([a-zA-Z0-9_]+)\\/admin").matcher(url);
            // if (m.find()) {
            // name = m.group(1);
            // }
            if (!currentUser.getName().equals(name)) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected AbstractFailureHandler getNativeFailureHandler(FilterInvocation fi) {
        // TODO Auto-generated method stub
        if (StringUtils.isNotBlank(failureUrl)) {
            RedirectFailureHandler failureHandler = new RedirectFailureHandler();
            failureHandler.setRedirectUrl(fi.getRequest().getContextPath() + failureUrl);
            return failureHandler;
        }
        return null;
    }

}
